package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.sprinmvc.LeaseException;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCode(String phone) {

        //拼接key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            //检查手机号是否已经发送，如果有的话并且在有效期内，返回信息；发送频繁
            //还有多长时间过期
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //有效时间
            Integer ttlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //发送间隔时间
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;
            if (ttlSec - expire < appLoginCodeResendTimeSec){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }


        }
        //生成验证码
        Random random = new Random();
        // 生成一个六位数的验证码
        int verificationCode = 100000 + random.nextInt(900000);
        System.out.println("验证吗：" + verificationCode);
        redisTemplate.opsForValue().set(key, String.valueOf(verificationCode), RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    @Override
    public String login(LoginVo loginVo) {

        //对前端发送过来的验证码和手机号进行验证
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String value = (String) redisTemplate.opsForValue().get(key);
        if (value == null || !value.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //查询用户
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo:: getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        //查看用户是否已经注册过
        if (userInfo == null) {
            //注册用户
            UserInfo user = new UserInfo();
            user.setPhone(loginVo.getPhone());
            user.setNickname("用户" + loginVo.getPhone());
            user.setAvatarUrl("https://pic.rmb.bdstatic.com/bjh/news/422d8fb919b80493a598aa2244c66ad4.jpeg");
            user.setStatus(BaseStatus.ENABLE);
            userInfoService.save(user);
        }
        //判断用户是否是可用状态
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //返回token
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }

    @Override
    public UserInfoVo info(String accessToken) {
//        //解析userId
//        Integer useId = (Integer) JwtUtil.parseToken(accessToken).get("userId");
//        //根据userid获取用户星系
//        UserInfo userInfo = userInfoService.getById(useId);
//        //将查询结果封装进userinfovo中
//        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
//
//        return userInfoVo;

        //1.解析userId
        Integer userId  = (Integer) JwtUtil.parseToken(accessToken).get("userId");
        //2.根据userId查询
        UserInfo userInfo = userInfoService.getById(userId);
        //3.封装vo
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
        return userInfoVo;
    }
}
